from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from alipay import AliPay
from dashopt import settings
from orders.models import OrderInfo


class MyAlipay(View):
    def __init__(self):
        super().__init__()
        self.alipay = AliPay(
            appid = settings.ALIPAY_APPID,
            #异步通知地址[有支付结果]
            app_notify_url=settings.ALIPAY_NOTIFY_URL,
            # 应用私钥[用于签名]
            app_private_key_string=open(settings.ALIPAY_KEY_DIR + 'app_private_key.pem').read(),
            # 支付宝公钥[用于签名]
            alipay_public_key_string=open(settings.ALIPAY_KEY_DIR + 'app_public_key.pem').read(),
            # 签名使用算法：非对称加密
            sign_type="RSA2",
            # False：线上环境 True:沙箱环境
            debug=True,
        )

class ReturnUrlView(MyAlipay):
    def get(self,request):
        """
        同步通知地址：只有支付信息，没有支付结果
        调用主动查询接口，查询支付结果
        """
        data = request.GET
        out_trade_no = data.get("out_trade_no")
        trade_no = data.get("trade_no")
        result = self.alipay.api_alipay_trade_query(
            out_trade_no=out_trade_no,
            trade_no=trade_no,
        )
        # 获取支付结果
        pay_result = result.get("trade_status")
        if pay_result =="TRADE_SUCCESS":
            order = OrderInfo.objects.get(order_id=out_trade_no)
            order.status = 2
            order.save()
            return HttpResponse("支付成功")
        else:
            return HttpResponse("支付失败")


